import React from "react";
// highlight-next-line
import { useDispatch,useSelector } from "react-redux";
import { Link } from "react-router-dom";

// highlight-next-line
import { 
  fetchNotifications,
  selectAllNotifications,
  fetchNotificationsWebsocket,
  selectNotificationsMetadata,
  useGetNotificationsQuery, 
} from "../features/notifications/notificationsSlice";

const Navbar = () => {
  // highlight-start
  const dispatch = useDispatch();

  useGetNotificationsQuery();

  const notificationsMetadata = useSelector(selectNotificationsMetadata);
  const numUnreadNotifications = notificationsMetadata.filter(
    (n) => !n.read
  ).length;

  //const notifications = useSelector(selectAllNotifications);
  //const numUnreadNotifications = notifications.filter((n) => !n.read).length;


  const fetchNewNotifications = () => {
    //dispatch(fetchNotifications());
    dispatch(fetchNotificationsWebsocket());
  };
  // highlight-end

  let unreadNotificationsBadge = (
    <span className="badge">{numUnreadNotifications ? numUnreadNotifications : 0}</span>
  );

  return (
    <nav>
      <section>
        <h1>Redux Essentials Example</h1>

        <div className="navContent">
          <div className="navLinks">
            <Link to="/">Posts</Link>
            <Link to="/users">Users</Link>
            <Link to="/notifications">Notifications {unreadNotificationsBadge}</Link>
          </div>
          <button className="button" onClick={fetchNewNotifications}>
            Refresh Notifications
          </button>
        </div>
      </section>
    </nav>
  );
};
export default Navbar;